//
//  LLOauthViewController.swift
//  WeiBoShiBing
//
//  Created by Bingo on 15/10/28.
//  Copyright © 2015年 Bingo. All rights reserved.
//

import UIKit
import SVProgressHUD

class LLOauthViewController: UIViewController {

    
    override func loadView() {
        view = webView
        
        webView.delegate = self
        
    }
    override func viewDidLoad() {
        super.viewDidLoad()
        

//       let 
//        view.backgroundColor = UIColor.brownColor()
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "取消", style: UIBarButtonItemStyle.Plain, target: self, action: "close")
        
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "填充", style: UIBarButtonItemStyle.Plain, target: self, action: "autoFill")
        let request = NSURLRequest(URL: LLNetworkTools.sharedInstance.oauthURL())
        webView.loadRequest(request)
        
    }
    
    
    func autoFill(){
        let js = "document.getElementById('userId').value='122702329@qq.com';" + "document.getElementById('passwd').value='07513653437.liu';"
        webView.stringByEvaluatingJavaScriptFromString(js)
    }
    
    func close() {
        SVProgressHUD.dismiss()
        dismissViewControllerAnimated(true, completion: nil)
    }

    private lazy var webView = UIWebView()
}

//MAPK: - 扩展
extension LLOauthViewController:UIWebViewDelegate{
    
    func webViewDidStartLoad(webView: UIWebView) {
        SVProgressHUD.showWithStatus("正在玩命加载...", maskType: SVProgressHUDMaskType.Black)
//        SVProgressHUD.show()
    }
    
    func webViewDidFinishLoad(webView: UIWebView) {
        SVProgressHUD.dismiss()
    }
    
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        let urlString = request.URL!.absoluteString
        
        print("urlString:\(urlString)")
        
        if !urlString.hasPrefix(LLNetworkTools.sharedInstance.redierct_uri){
        
            return true
        }
        if let query = request.URL?.query{
            let codeString = "code="
            
            if query.hasPrefix(codeString){
                let nsQuery = query as NSString
                
                let code = nsQuery.substringFromIndex(codeString.characters.count)
                loadAccessToken(code)
                
            }else{
                
            }
        }
        
        return false
    }
    
    func loadAccessToken(code:String){
        LLNetworkTools.sharedInstance.loadAccessToken(code){ (result,error) ->()in
            if error != nil || result == nil{
                self.netError("网络不给力")
              
                return
            }
            print("result：\(result)")
            let account = LLUserAccount(dict: result!)
        
            account.saveAccount()
            print("\(account)")
            account.loadUserInfo({ (error) -> () in
                if error != nil{
                    self.netError("加载用户数据出错....")
                    return
                }
            })
            
            print("account:\(account)")
//            SVProgressHUD.dismiss()
            self.close()
            
            (UIApplication.sharedApplication().delegate as!AppDelegate).switchRootController(false)
            
        }
    
    }
    private func netError(message:String){
        SVProgressHUD.showErrorWithStatus(message, maskType: SVProgressHUDMaskType.Black)
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (Int64)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), { () ->Void in
            self.close()
        })
    }

}